// pages/receiptList/receiptList.js
let request = require('../../operation/operation.js')
let userModel = require('../../models/user.js')
let noticeModel = require('../../models/notice.js')
let util = require('../../utils/util.js')
let bxt = require('../../utils/bxt.js')
let getReceiptListOperation = require('../../operation/getReceiptListOperation.js')
let reviewModalTemplate = require('../../template/reviewModal/reviewModal.js')

let receipteds = [] // 已签收数组信息
let noreceipts = [] // 未签收数组信息
let failReceipteds = [] // 未通过的签收数组信息
let videoCtx = null // 视频组件对象

let correct = false // 当前用户是否能批改签收
let receipt = null // 当前要批改的签收对象
let ReviewResult = { 'PASS': 1, 'FAIL': 2 }
let receiptReviewResult = ReviewResult.PASS // 当前签收对象批改结果
let reviewContent = '', reviewFlowerCount = 0

let sliderWidth = 96; // 需要设置slider的宽度，用于计算中间位置

let notice = null

Page({

  /**
   * 页面的初始数据
   */
  data: {
    receipts:[],  // 已签收数据
    noreceipts:[],  // 未签收数据
    tabs: [],
    activeIndex: 0,
    sliderOffset: 0,
    sliderLeft: 0,
    correct:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    notice = getApp().globalData.param.notice    
    this.initTabView()
    this.getReceipts(notice)

    getApp().notificationCenter.register(bxt.DELETE_REVIEW_MESSAGE, this, "handleDeleteReviewMessage");
    getApp().notificationCenter.register(bxt.REVIEW_FAIL_MESSAGE, this, "handleReviewFailMessage");
    getApp().notificationCenter.register(bxt.REVIEW_PASS_MESSAGE, this, "handleReviewPassMessage");
    getApp().notificationCenter.register(bxt.REVIEW_UPDATE_MESSAGE, this, "handleReviewUpdateMessage");
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    correct = false    
    videoCtx = null
    receipteds = []
    noreceipts = []
    failReceipteds = []
    reviewFlowerCount = 0
    notice = null

    getApp().notificationCenter.remove(bxt.DELETE_REVIEW_MESSAGE, this);
    getApp().notificationCenter.remove(bxt.REVIEW_FAIL_MESSAGE, this);
    getApp().notificationCenter.remove(bxt.REVIEW_UPDATE_MESSAGE, this);
  },

  initTabView:function() {
    let that = this, tabsCount = 2,tabs = []

    if ('confirm' == notice.receiptRequirement) {
      tabs = ["已签收（" + receipteds.length + "）", "未签收（" + noreceipts.length + "）"]
    }else {
      tabs = ["已签收（" + receipteds.length + "）", "未签收（" + noreceipts.length + "）", "未通过 (" + failReceipteds.length + ")"]
      tabsCount = 3
    }

    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          tabs: tabs,
          sliderLeft: (res.windowWidth / that.data.tabs.length - sliderWidth) / tabsCount,
          sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex
        });
      }
    });
  },

  /**
   * 单击tab事件处理函数
   */
  tabClick: function (e) {
    this.switchTabView(e.currentTarget.id)

    this.setData({      
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id
    })
  },

  switchTabView:function(acticeIndex) {
    let tmpReceipts = null
    if ('0' == acticeIndex) {
      tmpReceipts = receipteds
    } else if ('2' == acticeIndex) {
      tmpReceipts = failReceipteds
    }

    if (null != tmpReceipts) {
      this.setData({
        receipts: tmpReceipts,
      })
    }
  },


  // /**
  //  * 单击列表行事件处理函数
  //  */
  // showReceipteDetail:function(event){
  //   let receipt = event.currentTarget.dataset.receipt
  //   if (receipt.receipt) {
  //     getApp().globalData.param = { 'notice': getApp().globalData.param.notice, 'receipt': receipt.receipt }
  //     wx.navigateTo({
  //       url: '../receiptDetail/receiptDetail',
  //     })
  //   }else {
  //     wx.showToast({
  //       title: '未签收',
  //       icon: 'none'
  //     })
  //   }
  // },

  /**
   * 获取这条通知的签收情况
   */
  getReceipts:function(notice) {
    var that = this;

    getReceiptListOperation.getReceiptList(notice.sid,notice.klass.sid)
    .then(res => {
      that.initCorrectPower()
      that.initReceiptListView(res)
      that.setData({
        notice: notice
      })
    })
  },

  /**
   * 初始化签收列表
   */
  initReceiptListView: function (receipts) {
    receipteds = [], noreceipts = [], failReceipteds = []

    for (let index = 0, length = receipts.length; index < length; index++) {
      if (receipts[index].receipt) {
        receipts[index].receipt.uiCreatedAt = util.formatDateTime(receipts[index].receipt.createdAt)
        receipteds.push(receipts[index])
        if (receipts[index].receipt.review && receipts[index].receipt.review.result == ReviewResult.FAIL) {
          failReceipteds.push(receipts[index])
        }
      } else {
        noreceipts.push(receipts[index])
      }
    }

    this.setData({
      receipts: receipteds,
      noreceipts: noreceipts,
      failReceipteds: failReceipteds
    })

    this.initTabView()
  },

  /**
   * 批改事件成功后处理函数
   */
  refreshReceiptListView:function(review) {
    failReceipteds = []

    for (let index = 0, length = receipteds.length; index < length; index++) {
      console.log(receipteds[index].receipt)
      if (receipteds[index].receipt.sid == review.receiptSid) {
        receipteds[index].receipt.review = review
      }

      if (null != receipteds[index].receipt.review && receipteds[index].receipt.review.result == ReviewResult.FAIL) {
        failReceipteds.push(receipteds[index])
      }
    }

    this.setData({
      receipts: receipteds,
    })
  },

  previewImage:function(event) {
    let images = []
    for (let index = 0, length = event.currentTarget.dataset.images.length;index < length;index++) {
      images.push(event.currentTarget.dataset.images[index].url)
    }

    wx.previewImage({
      current: event.currentTarget.dataset.path.url,
      urls: images
    })
  },

    /**
     * 处理删除批改事件函数
      * @param object
     */
  handleDeleteReviewMessage:function(object) {
    let receipt = object.receipt

    // 修改未通过签收数据
    for (let index = 0, length = failReceipteds.length; index < length; index++) {
      if (failReceipteds[index].receipt.sid == receipt.sid) {
        failReceipteds.splice(index, 1)
      }
    }

    // 修改已签收数据
    for (let index = 0 ,length = receipteds.length; index < length; index++) {
      if (receipteds[index].receipt.sid == receipt.sid) {
        receipteds[index].receipt.review = null
      }
    }
    
    this.switchTabView(this.data.activeIndex)
    this.initTabView()
  },

    handleReviewPassMessage:function(object) {
        let review = object.review

        // 修改未通过签收数据
        for (let index = 0, length = failReceipteds.length; index < length; index++) {
            if (failReceipteds[index].receipt.sid == review.receiptSid) {
                failReceipteds.splice(index, 1)
            }
        }

        // 修改已签收数据
        for (let index = 0 ,length = receipteds.length; index < length; index++) {
            if (receipteds[index].receipt.sid == review.receiptSid) {
                receipteds[index].receipt.review = review
            }
        }

        this.switchTabView(this.data.activeIndex)
        this.initTabView()
    },

    handleReviewFailMessage:function(object) {
        this.refreshReceiptListView(object.review)
        this.initTabView()
    },

    handleReviewUpdateMessage:function(object) {
        let review = object.review

        // 修改未通过签收数据
        for (let index = 0, length = failReceipteds.length; index < length; index++) {
            if (failReceipteds[index].receipt.sid == review.receiptSid) {
                failReceipteds[index].receipt.review = review
            }
        }

        // 修改已签收数据
        for (let index = 0 ,length = receipteds.length; index < length; index++) {
            if (receipteds[index].receipt.sid == review.receiptSid) {
                receipteds[index].receipt.review = review
            }
        }

        this.switchTabView(this.data.activeIndex)
    },

  /**
   * 单击视频播放事件处理函数
   * 暂停正在播放的视频
   */
  onPlayVideo:function(event) {
    wx.navigateTo({
      url: '../playVideo/playVideo?src=' + event.currentTarget.dataset.receipt.receipt.video.url,
    })
    // if (videoCtx && videoCtx.domId != event.currentTarget.id) {
    //   videoCtx.pause()
    // }

    // videoCtx = wx.createVideoContext(event.currentTarget.id)

  },

  /**
   * 检查是否能批改签收，必须具有下面2个条件
   * 1 通知签收模式非“无”
   * 2 班主任老师
   */
  initCorrectPower:function() {
    correct = false
    if ('confirm' != notice.receiptRequirement) {      
      if (userModel.HEAD_TEACHER == userModel.getRole(notice.klass).role) {
        correct = true
      }
    }

    this.setData({
      correct: correct
    })
  },

  bindKeyInput:function(event) {
    reviewContent = event.detail.value
  },

  onRate: function (event) {
    reviewFlowerCount = parseInt(event.currentTarget.id)
    reviewModalTemplate.setFlowerCount(event.currentTarget.id)
  },

  /**
   * 点击批改按钮事件处理函数
   */
  onReview:function(event) {
    let that = this
    receipt = event.currentTarget.dataset.receipt.receipt
    if (null == receipt.review) {
      wx.showActionSheet({
        itemList: ['通过','不通过'],
        success: function(res) {  
          reviewContent = ''
          receiptReviewResult = res.tapIndex + 1  
          if (noticeModel.REVIEW_RESULT.FAIL == receiptReviewResult) {
            reviewFlowerCount = 0
          } else {
            reviewFlowerCount = 0
          }    
          reviewModalTemplate.show(that)
          reviewModalTemplate.initRate(receiptReviewResult, reviewFlowerCount)
        }      
      })
    }else {
      getApp().globalData.param.receipt = receipt
      wx.navigateTo({
        url: '../reviewDetail/reviewDetail' 
      })
    }    
  },

  onConfirm:function() {
    let that = this
    if (null == receipt.review) {
      reviewModalTemplate.createReview(receipt.sid, receiptReviewResult, reviewContent, reviewFlowerCount).then(res => {
        reviewModalTemplate.cancel()
        if (ReviewResult.FAIL == receiptReviewResult) {
          notice = noticeModel.updateNoticeReceiptStatus(notice,1)
          let review = res
          getApp().notificationCenter.post(bxt.REVIEW_FAIL_MESSAGE, { notice,review })
        }else {
          that.refreshReceiptListView(res)
        }
      })
    }
  },

  onCancel:function() {
    reviewModalTemplate.cancel()
  }

})